package cn.tedu.imop.emqx.emqx;
import cn.tedu.imop.emqx.service.MqttConsumer;
import org.springframework.context.annotation.Configuration;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;

/**
 * EMQX消息中间件的 连接配置
 */
@Configuration
public class MqttConfiguration {

    /**
     * 用户名 这些配置类的信息 应该放到 配置文件 或者
     * nacos 中 (nacos 提供了服务注册和配置管理)
     */
    private String userName = "admin";

    /**
     * 密码
     */
    private String password = "public";

    /**
     * 连接地址 tcp协议 端口 1883
     */
    private String host = "tcp://localhost:1883";

    /**
     * 客户端id  启动多个订单服务 通过 getRandom() 会生成不同的 客户端id
     */
    private String clientId = "order_service_client_" + getRandom();


    private Integer getRandom(){
        Random random = new Random();
        return random.nextInt(100);
    }

    @Bean
    public MqttClient mqttClient() throws Exception {

        //通过连接地址和客户端id和emqx进行连接
        //客户端id 目的是要告诉我们的服务器 谁在连接它
        MqttClient mqttClient = new MqttClient(host, clientId);
        //连接相关的配置
        MqttConnectOptions conOpts = new MqttConnectOptions();
        //配置用户名
        conOpts.setUserName(userName);
        //配置密码
        conOpts.setPassword(password.toCharArray());
        //自动重连
        conOpts.setAutomaticReconnect(true);
        //版本号设置
        conOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        //清理会话session
        conOpts.setCleanSession(true);
        //通过java里的关键字 new 创建一个MqttConsumer
        //类型的对象 名字是  mqttConsumer 回调类
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient);
        //把mqttConsumer回调类,设置给mqttClient
        //同时要在 mqttConsumer 里面使用 容器里的 mqttClient,通过mqttClient来订阅topic
        //把mqttClient 设置给mqttConsumer 怎么整 ???
        mqttClient.setCallback(mqttConsumer);
        //基于上面配置的 conOpts 进行连接 和emqx
        mqttClient.connect(conOpts);
        return mqttClient;
    }

}
